package cn.ffcs.bpmpvc.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.echoice.paper.PageBean;
import org.echoice.paper.PageNavi;
import org.echoice.spring.BaseController;
import org.springframework.web.servlet.ModelAndView;

import cn.ffcs.bpmpvc.dao.ProductFlowDao;
import cn.ffcs.bpmpvc.services.ProductFlowService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.utils.FlowContextUtil;
import cn.ffcs.bpmpvc.web.util.UserContextUtil;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.bpmpvc.web.views.ProcessView;
import cn.ffcs.bpmpvc.web.views.ProductReferAttachView;
import cn.ffcs.bpmpvc.web.views.TaskView;
import cn.ffcs.organ.model.Organization;
import cn.ffcs.organ.model.Person;
import cn.ffcs.product.model.Product;
import cn.ffcs.product.model.ProductManager;
import cn.ffcs.productdict.model.ProductInfo;
import cn.ffcs.ref.model.ProductRefSort;
import cn.ffcs.security.model.User;
import cn.ffcs.sort.model.ProductSort;
import cn.ffcs.system.dict.model.Dict;
/**
 * 新产品发布流程
 * @author wujy
 *
 */
public class ProductFlowController extends BaseController {
	private ProductFlowService productFlowService;
	private final String basePath="/bpm/productFLow/";
	@Override
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		
		Product searchForm=new Product();
		bindObject(request, searchForm);
		PageBean pageBean=productFlowService.getProductFlowDao().searchProductPageList(searchForm, getPageNo(request), getPageSize(request));
		request.setAttribute("dataList", pageBean.getDataList());
		request.setAttribute("pageNaviStr", PageNavi.getPageNaviButton(request, pageBean));
		return new ModelAndView(basePath+"index.jsp");
	}
	
	public ModelAndView applyInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		User user =UserContextUtil.getUserContext(request).getCurrUser();
		Organization startDept=productFlowService.getAppBusinessReqService().getOrgByPerson(user.getPerson());
		String processId=productFlowService.getProcessId();
		ProcessView processView=productFlowService.getProcessPvcService().getInitProcessInfo(processId,null,startDept);
		request.setAttribute("processView", processView);
		//查看上传的文档类型
	    List refeTypeList=productFlowService.getRefeTypeList();
	    request.setAttribute("refeTypeList", refeTypeList);
		return new ModelAndView(basePath+"apply_init.jsp");
	}
	/**
	 * 启动流程
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView saveStartFlow(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
	    boolean isCommit=FlowContextUtil.isCommit(request);
	    User user =UserContextUtil.getUserContext(request).getCurrUser();
	    List<TaskAssignBean> nextTasksList = FlowContextUtil.getNextTaskUserList(request);
	    String processId=request.getParameter("processId");
	    Product applyForm=new Product();
	    bindObject(request, applyForm);
	    Date curDate=new Date();
	    applyForm.setEnd(curDate);
	    applyForm.setBegin(new Date());
	    applyForm.setCreator(user.getUserID());
	    
	    //取关联产品类型 refSort
	    String productSortIdArr[]=request.getParameterValues("productSortId");
	    //动态产品属性
	    String propertyValueArr[]=request.getParameterValues("propertyValue");
	    String infoIdsArr[]=request.getParameterValues("infoIds");
	    
	    String returnMsg=FlowContextUtil.setStartFlowMsg(isCommit);
	    try{
	    	productFlowService.saveAndStartFlow(processId, user.getPerson(), nextTasksList, isCommit, applyForm, productSortIdArr,propertyValueArr,infoIdsArr,request);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            returnMsg="提交失败，原因："+e.getMessage();
        }
	    FlowContextUtil.setReturnMsgAttr(request, returnMsg);
		return new ModelAndView(FlowContextUtil.JSP_SUCCESS);
	}
	
	/**
	 * 查看任务明细
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView showDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String toPage=request.getParameter("toPage");
        String flowTaskId=request.getParameter("flowTaskId");
        TaskView taskView=null;
        Map dataMap=initAppData(request);
        Product product=(Product)dataMap.get("product");
        if(StringUtils.equalsIgnoreCase(toPage, "showDeptCheck")||StringUtils.equalsIgnoreCase(toPage, "showApply")){
        	Person person=productFlowService.getAppBusinessReqService().getAppBusinessReqDao().getPersonByUserID(product.getCreator());
        	Organization startDept=productFlowService.getAppBusinessReqService().getOrgByPerson(person);
        	taskView=productFlowService.getTaskService().getTaskView(flowTaskId,null,startDept);
        }else if(StringUtils.equalsIgnoreCase(toPage, "showCompCheck")){
        	taskView=productFlowService.getTaskService().getTaskView(flowTaskId,product.getIsClient(),null);
        }else{
        	taskView=productFlowService.getTaskService().getTaskView(flowTaskId);
        }
        
        String taskType=taskView.getProcTranRecord().getTaskType();
        
        request.setAttribute("taskView", taskView);
        if("03".equalsIgnoreCase(taskType)){
        	return new ModelAndView(basePath+"showForRedo.jsp",dataMap);
        }
        
        if(StringUtils.equalsIgnoreCase(toPage, "showApply")){
        	//查看上传的文档类型
    	    List<Dict> refeTypeList=productFlowService.getRefeTypeList();
    	    //对于有上传过的文档类型，不在做前端校验
    	    Map<String, String> attachTypeMap=new HashMap<String, String>();
    	    List<ProductReferAttachView> productReferAttachList=(List<ProductReferAttachView>)dataMap.get("productReferAttachList");
    		for (ProductReferAttachView tmp : productReferAttachList) {
    			String key=tmp.getProductReference().getReferenceType().getId().toString();
    			attachTypeMap.put(key, key);
    		}
    		String tmp=null;
    		String isClinet=product.getIsClient();
    		for (Dict dict : refeTypeList) {
    			//
    			if("1".equals(isClinet)){
    				if(StringUtils.indexOf(dict.getKeyValue(), "productClient")!=-1){
    					dict.setNote("y");
    				}
    			}
    			if("y".equals(dict.getNote())){
    				tmp=attachTypeMap.get(dict.getId().toString());
    				if(StringUtils.isNotBlank(tmp)){
    					dict.setNote("n");
    				}
    			}
			}
    	    request.setAttribute("refeTypeList", refeTypeList);
    	    return new ModelAndView(basePath+"showApply.jsp",dataMap);
        }else if(StringUtils.equalsIgnoreCase(toPage, "showArchive")){
        	return new ModelAndView(basePath+"showArchive.jsp",dataMap);
        }
		return new ModelAndView(basePath+"showDetail.jsp",dataMap);
	}
	/**
	 * 保存提交申请任务
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView commitApplyTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
		boolean isCommit=FlowContextUtil.isCommit(request);
		String flowTaskId=request.getParameter("flowTaskId");
		String procinstId=request.getParameter("procinstId");
		String content=request.getParameter("commentComtent");
		List<TaskAssignBean> nextTasksList = FlowContextUtil.getNextTaskUserList(request);
		String returnMsg=FlowContextUtil.setCommitTaskMsg(isCommit);
		Product applyForm=new Product();
	    bindObject(request, applyForm);
	    //取关联产品类型 refSort
	    String productSortIdArr[]=request.getParameterValues("productSortId");
	    //动态产品属性
	    String propertyValueArr[]=request.getParameterValues("propertyValue");
	    String infoIdsArr[]=request.getParameterValues("infoIds");
		try{
			productFlowService.commitApplyTask(flowTaskId, content, procinstId, nextTasksList, isCommit, applyForm,productSortIdArr,propertyValueArr,infoIdsArr,request);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnMsg="操作失败，原因："+e.getMessage();
		}
		FlowContextUtil.setReturnMsgAttr(request, returnMsg);
		return new ModelAndView(FlowContextUtil.JSP_SUCCESS);
	}
	/**
	 * 提交归档任务
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView commitArchiveTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
		boolean isCommit=FlowContextUtil.isCommit(request);
		String flowTaskId=request.getParameter("flowTaskId");
		String procinstId=request.getParameter("procinstId");
		String content=request.getParameter("commentComtent");
		List<TaskAssignBean> nextTasksList = FlowContextUtil.getNextTaskUserList(request);
		String returnMsg=FlowContextUtil.setCommitTaskMsg(isCommit);
		try{
			productFlowService.commitArchiveTask(flowTaskId, content, procinstId, nextTasksList, isCommit);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnMsg="操作失败，原因："+e.getMessage();
		}
		FlowContextUtil.setReturnMsgAttr(request, returnMsg);
		return new ModelAndView(FlowContextUtil.JSP_SUCCESS);
	}
	
	private Map initAppData(HttpServletRequest request){
		String procinstId=request.getParameter("procinstId");
		ProductFlowDao productFlowDao=productFlowService.getProductFlowDao();
		Product product=productFlowDao.getByProinstId(procinstId);
		String productId=product.getId().toString();
		Map map=new HashMap();
		map.put("product", product);
		//取产品 把对应的目录
		List<ProductRefSort> productRefSorts=productFlowDao.findProductRefSortList(productId);
		ProductSort productSort=null;
		for (ProductRefSort productRefSort : productRefSorts) {
			productSort=(ProductSort)productFlowService.getProductSortService().findById(Integer.valueOf(productRefSort.getSort()));
			 productSort.setName(this.findSortPath(productSort.getId()+""));
             if("1".equals(productSort.getSortType())){
            	 request.setAttribute("jtProductSort", productSort);
             }else if("2".equals(productSort.getSortType())){
                 request.setAttribute("shProductSort", productSort);
             }
		}
		
		//取产品图片
		List imageAttachList=productFlowService.getAttachDAO().findAttachList(Product.class.getName(), productId);
		map.put("imageAttachList", imageAttachList);
		//取产品文档
		List<ProductReferAttachView> productReferAttachList=productFlowService.getProductFlowDao().findProductReferAttachList(productId);
		map.put("productReferAttachList", productReferAttachList);
		//
		
		
		//取产品主要负责人与其它负责人
		Iterator it = product.getProductManagers().iterator();
        String mainPersons = "";
        String mainPersonNames = "";
        String persons = "";
        String personNames = "";
		while (it.hasNext()) {
			ProductManager productManager = (ProductManager) it.next();
			Person person = productManager.getPerson();
			if (productManager.getIsPrimary().equals("1")) {
				mainPersons += person.getId() + ",";
				mainPersonNames += person.getName() + ",";
			} else {
				persons += person.getId() + ",";
				personNames += person.getName() + ",";
			}
		}
		if (StringUtils.isNotBlank(mainPersons)) {
			mainPersons = mainPersons.substring(0, mainPersons.length() - 1);
			mainPersonNames = mainPersonNames.substring(0, mainPersonNames.length() - 1);
			map.put("mainPersons", mainPersons);
			map.put("mainPersonNames", mainPersonNames);
		}
		if (StringUtils.isNotBlank(persons)) {
			persons = persons.substring(0, persons.length() - 1);
			personNames = personNames.substring(0, personNames.length() - 1);
			map.put("persons", persons);
			map.put("personNames", personNames);
		}
        //取产品附加属性
		List<ProductInfo> productInfos=productFlowDao.findProductInfos(product.getId().toString());
		map.put("productInfos", productInfos);
		return map;
	}
	
	private String findSortPath(String sortId){
        String str = productFlowService.getProductSortService().findAllSortById(sortId+"")+"";
        str=str.replace("集团产品目录:", "");
        str=str.replace("福建省产品目录:", "");
        str=str.replace(" -> ", "/");
        return str;
    }
	public ModelAndView showInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String procinstId=request.getParameter("procinstId");
		ProcessInstView processInstView=productFlowService.getProcessPvcService().getProcessInstView(Integer.valueOf(procinstId));
		FlowContextUtil.setProcessInstTaskInfo(productFlowService.getTaskService(),processInstView,procinstId,request);
		Map dataMap=initAppData(request);
		request.setAttribute("taskView", processInstView);
		return new ModelAndView(basePath+"showInfo.jsp",dataMap);
	}
	
	public ProductFlowService getProductFlowService() {
		return productFlowService;
	}
	public void setProductFlowService(ProductFlowService productFlowService) {
		this.productFlowService = productFlowService;
	}
	
}
